//
//  NetWorkRequest.swift
//  StoryMeeting
//
//  Created by Lee on 2018/9/21.
//  Copyright © 2018年 Lee. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

private let NetWorkRequestShareInstance = NetWorkRequest()

class NetWorkRequest: NSObject {
    
    var NetState = false
    var NetStateString:String?
    let manager = NetworkReachabilityManager()
    private var noNetView:CustomAlertView?
    
    class var sharedInstance:NetWorkRequest {
        return NetWorkRequestShareInstance
    }
}

extension NetWorkRequest{
    
    func getHTMLRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {
        
        let url = UrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        var request = URLRequest(url: URL(string: url!)!)
        request.timeoutInterval = 8
        request.httpMethod = HTTPMethod.get.rawValue
        request.setValue("text/html;charset=UTF-8", forHTTPHeaderField:"Content-Type")
        request.setValue("text/htm", forHTTPHeaderField: "Accept")
        Alamofire.request(request).responseJSON { (response) in
            switch response.result{
            case .success:
                //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
                if let value = response.result.value as? [String:AnyObject]{
                    success(value)
                }
                
            case .failure(let error):
                failure(error)
                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }
    
    func getRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {

        let url = UrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        var request = URLRequest(url: URL(string: url!)!)
        request.timeoutInterval = 8
        request.httpMethod = HTTPMethod.get.rawValue
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField:"Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        
        Alamofire.request(request).responseJSON { (response) in
            switch response.result{
            case .success:
                //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
                if let value = response.result.value as? [String:AnyObject]{
                    success(value)
                }

            case .failure(let error):
                failure(error)
//                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }
    
    // MARK:post with body request
    /// - Parameters:
    ///   - type: 需要的json字符串类型 dic为字典 arr为数组
    ///   - UrlString: 请求url
    ///   - paramer: params
    ///   - success: 成功回调
    ///   - failure: 失败回调
    func postWithBodyRequest(type:String, UrlString:String, paramer:Any, success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()){
        
        var request = URLRequest(url: URL(string: UrlString)!)
        request.timeoutInterval = 8
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField:"Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.httpBody = type == "dic" ? JsonAndStringMethod().getJSONStringFromDictionary(dictionary: paramer as! NSDictionary).data(using: .utf8, allowLossyConversion: false) : JsonAndStringMethod().getJSONStringFromArray(array: paramer as! NSArray).data(using: .utf8, allowLossyConversion: false)
        
        Alamofire.request(request).responseJSON { (response) in
            switch response.result{
            case .success:
                if let value = response.result.value as? [String:AnyObject]{
                    success(value)
                }
            case .failure(let error):
                failure(error)
                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }
    
    // MARK:post with NoBody request
    ///   - Parameters:
    ///   - UrlString: 请求url
    ///   - paramer: params
    ///   - success: 成功回调
    ///   - failure: 失败回调
    func postWithNoBodyRequest(UrlString:String, paramer:[String:Any]?, success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()){
        let url = UrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        Alamofire.request(url ?? "", method: .post, parameters: paramer, encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
            switch response.result{
            case .success:
                if let value = response.result.value as? [String:AnyObject]{
                    success(value)
                }
            case .failure(let error):
                failure(error)
                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }

    // MARK:post with request
    ///   - Parameters:
    ///   - UrlString: 请求url
    ///   - paramer: params
    ///   - success: 成功回调
    ///   - failure: 失败回调
    func postWithRequest(UrlString:String, paramer:[String:Any]?, success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()){
        
        let url = UrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        var request = URLRequest(url: URL(string: url!)!)
        request.timeoutInterval = 8
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField:"Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        
        Alamofire.request(request).responseJSON { (response) in
            switch response.result{
            case .success:
                if let value = response.result.value as? [String:AnyObject]{
                    success(value)
                }
            case .failure(let error):
                failure(error)
                LYProgressHUD.showMessage("网络错误！")
            }
        }
    }
    
    
    /// 上传图片
    ///
    /// - Parameters:
    ///   - type: 类型 image-图片  video-视频  audio-音频
    ///   - UrlString: 请求url
    ///   - params: params
    ///   - data: 资源
    ///   - name: 文件名字
    ///   - success: 成功回调
    ///   - failure: 失败回调
    func upLoadImageRequest(type:String,UrlString:String,params:[String:Any]?,data:[Data],name:[String],success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()){
        let headers = ["content-type":"multipart/form-data","accept":"application/json"]
//        let PathUrl = BaseUrl+UrlString
        Alamofire.upload(multipartFormData: { (multipartforData) in

            for i in 0..<data.count{
                
                var fileName:String?
                
                if type == "image" {
                    
                    fileName = String.init(describing: NSDate()) + "\(i).jpg"
                    multipartforData.append(data[i], withName: "file", fileName: fileName ?? "", mimeType: "image/jpeg")
                    
                }else if type == "video" {
                    
                    fileName = String.init(describing: NSDate()) + "\(i).mp4"
                    multipartforData.append(data[i], withName: "file", fileName: fileName ?? "", mimeType: "video/mp4")
                    
                }else if type == "audio" {
                    
                    fileName = String.init(describing: NSDate()) + "\(i).amr"
                    multipartforData.append(data[i], withName: "file", fileName: fileName ?? "", mimeType: "audio/mpeg")
                }
            }
            
        }, to: UrlString,
           headers: headers,
           encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        success(value)
                        let json = JSON(value)
                        print(json)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
                LYProgressHUD.showMessage("网络错误！")
            }
        })
    }
    
        
    func currentNetReachability(){

        var statusStr: String?
        self.manager?.listener = { status in
            switch status {
            case .unknown://未识别的网络
                statusStr = "unknown"
                break
            case .notReachable://不可用的网络(未连接)
                statusStr = "notReachable"

                self.noNetView = CustomAlertView.init(frame: MAINSCREEN, title: "提示", message: "当前无网络状态，请重新检查网络", contentArr: ["确认"], btnTitleColorArr: nil, width: MAINWIDTH - 100, btnDirection:0) { (selectTag) in
                    
                }
                self.noNetView?.showPopView()
                
            case .reachable:
                self.noNetView?.dismissPopView()
                if (self.manager?.isReachableOnWWAN)! {//2G,3G,4G...的网络
                    statusStr = "2G,3G,4G..."
                } else if (self.manager?.isReachableOnEthernetOrWiFi)! {//Wifi
                    statusStr = "Wifi";
                }
                break
            }
            self.NetState = statusStr == "notReachable" ? false : true
            self.NetStateString = statusStr
            NotificationCenter.default.post(name: NSNotification.Name("NetStatueNotification"), object:nil)

            print(message: statusStr as Any)
        }
        self.manager?.startListening()
    }
}


